package kcms.assignment.action;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import kcms.assignment.service.AssignmentService;
import kcms.course.service.CourseService;
import kcms.db.Assign;
import kcms.db.Assignment;
import kcms.db.Assignmentcontent;
import kcms.db.CourseJiaoke;
import kcms.db.User;
import kcms.user.service.UserService;

import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVPrinter;
import org.apache.commons.csv.CSVRecord;
import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ActionContext;

@Controller("AssignemntAction")
@Scope("prototype")
public class AssignmentAction {
	private static final long serialVersionUID = 1L;
	@Resource
	private AssignmentService assignmentservice;
	@Resource
	private UserService userservice;
	@Resource
	private CourseService courseservice;
	private List<CourseJiaoke> cj;
	private String[] checkbox;
	private String assignmentname,description;
	private String duetime;
	private List<Assign> assign;
	private String aid;
	private InputStream inputStream;
	private String fileName;
	private String[] downLoadPaths;
	private String[] downLoadNames;
	private String radio;
	@Resource
	private Assignment as;
	private Assign ass;
	private boolean timeflag;
	private boolean submitflag;
	private File doc;   
    private String docFileName;   
    private String docContentType;
    private static String localpath="D:/kcms/uploadedassignfile";
    private static String csvlocalpath="D:/kcms/csvtemplate";
    private static String uploadcsvlocalpath="D:/kcms/csvscore";
    
    @Resource
    private List<CourseJiaoke> c1,c2;
    @Resource
    private List<Assign> a1,assignlist,downassign;
    private String cid,csn,assignmentsn;
    @Resource
    private CourseJiaoke tempc2,tempc1;
    @Resource
    private Assign tempa1;
    @Resource
	private Assignmentcontent asc;
    private List<Assign> listassign;
    private OutputStream res;
	private ZipOutputStream zos;
	
	
	
	private User user;
	private List<CourseJiaoke> cr;
    private String chkbox;
	
	
	//CSV文件分隔符
  	private static final String NEW_LINE_SEPARATOR = "\n";
  	
  	//CSV文件头
  	private static final Object[] FILE_HEADER = {"学号","姓名","分数","评语"};
	public String newTask(){
		cj=this.courseservice.getAllCourseTeachBy((User) ActionContext.getContext().getSession().get("user"));
		return "listcoursesuccess";
	}
	
	public String submitAssignmentTask() throws ParseException{
		String[] temp;
		boolean flag=false;
		for(String c:checkbox){
			temp=c.split("@");
			as.setCid(temp[0]);
			as.setCsn(temp[1]);
			as.setAssignmentname(assignmentname);
			as.setDescription(description);
			System.out.println(duetime);
			as.setDuetime(duetime);
			if(!assignmentservice.saveNewTask(as))
				flag=true;
		}
		if(flag)
			return "savetasksomefail";
		else
			return "savetasksuccess";
	}
	public String stuTaskList(){
		
		assign=assignmentservice.getAllAssignBySid(((User) ActionContext.getContext().getSession().get("user")).getId());
		return "stulistsuccess";
	}
	public String taskDetail(){
		ass=assignmentservice.getAssignByAid(aid);
		if(ass.getDuetime().getTime()<new Date().getTime())
			timeflag=false;
		else
			timeflag=true;//可提交
		if(ass.getResource()==null)
			setSubmitflag(false);//没提交过
		else
			setSubmitflag(true);
		return "detaillistsuccess";
	}
	
	public String submitAssign() throws Exception{
	ServletActionContext.getRequest().setCharacterEncoding("UTF-8");
	if (doc != null) {
		//String realpath = ServletActionContext.getServletContext().getRealPath("/uploadedassignfile");
        File savedir=new File(localpath);
        if(!savedir.getParentFile().exists())
            savedir.getParentFile().mkdirs();
        Assign tempa;
        if((tempa=this.assignmentservice.getAssignByAid(aid)).getResource()!=null){		//在表中找到了对应assignmentid
        		File delfile= new File(savedir, tempa.getResource());
        		if(delfile.isFile()&&delfile.exists())
        			delfile.delete();//如果文件存在，同时删除文件
        		asc=assignmentservice.getAssignmentcontentByAid(tempa.getAssignmentid());
        		assignmentservice.deleteAssignmentcontent(asc);//删除对应数据库记录
        }
        //此时assignmentcontent肯定没有记录，开始存文件并保存记录到表
        String filename=generateFileName(docFileName);
        File savefile = new File(savedir, filename);
        FileUtils.copyFile(doc, savefile);
        assignmentservice.saveContentRecord(tempa.getAssignmentid(),docFileName,filename);//存失败为false
    }
	return "submitsuccess";
	}
	private String generateFileName(String fileName) {   
        DateFormat format = new SimpleDateFormat("yyMMddHHmmss");   
        String formatDate = format.format(new Date());     
        int random = new Random().nextInt(10000);   
        int position = fileName.lastIndexOf(".");   
        String extension = fileName.substring(position);   
        return formatDate + random + extension;   
    }
	
	
	public String deleteAssign(){
		if(assignmentservice.deleteAssign(assignmentsn))
			return "deleteassignsuccess";
		else
			return "deleteassignfail";
	}
	
	
	public String ListAssign(){
		/*System.out.println(cid);
		System.out.println(csn);
		System.out.println(assignmentsn);
		tempc1.setCid("qaz");
		tempc1.setTime("请选择科目");
		tempc2.setCsn("wsx");
		tempc2.setTime("请选择时间");
		tempa1.setAssignmentsn(-1);
		tempa1.setAssignmentname("请选择作业名");
		String flag;
		if(cid!=null&&cid.equals("qaz"))
		flag=cid;
		else if(csn!=null&&csn.equals("wsx"))
		flag=csn;
		else if(assignmentsn!=null&&assignmentsn.equals("-1"))
			flag=assignmentsn.toString();
		else
			flag=null;
		System.out.println(flag);
		if(flag==null||flag.equals("qaz")){
			System.out.println("go1");
			c1.clear();
			c2.clear();
			a1.clear();
			c1=courseservice.getAllCourseTeachBy(((User) ActionContext.getContext().getSession().get("user")));
			c2.add(tempc2);
			a1.add(tempa1);	
		}
		else if(flag.equals("wsx")){
			System.out.println("go2");
			c1.clear();
			c2.clear();
			a1.clear();
			c1=courseservice.getAllCourseTeachBy(((User) ActionContext.getContext().getSession().get("user")));
			c2=courseservice.getAllCourseByCid(cid);
			a1.add(tempa1);
		}else {
			System.out.println("go3");
			c1.clear();
			c2.clear();
			a1.clear();
			c1=courseservice.getAllCourseTeachBy(((User) ActionContext.getContext().getSession().get("user")));
			c2=courseservice.getAllCourseByCid(cid);
			a1=assignmentservice.getAllAssignByCidCsn(cid,csn);
		}*/
		
		//老师选择自己所教授的课程单选
		
			user=(User) ActionContext.getContext().getSession().get("user");
			cr=courseservice.getAllCourseTeachBy(user);
			if(chkbox!=null){
				String[] tempsplit=chkbox.split("@");
				
				int flag=0;
				List<Assign> templ = assignmentservice.getAllAssignByCidCsn(tempsplit[0],tempsplit[1]);
				Assign[] temp = (Assign[])templ.toArray(new Assign[templ.size()]);
				for(int i=0;i<temp.length;i++){
					for(int j=i+1;j<temp.length;j++){
						if(temp[i].getAssignmentsn().intValue()==temp[j].getAssignmentsn().intValue()){
							temp[j].setAssignmentsn(-1);
							flag++;
						}
					}
				}
				Assign[] tempa = new Assign[templ.size()-flag];
				int t=0;
				for(int p=0;p<temp.length;p++){
					if(temp[p].getAssignmentsn().intValue()!=-1){
						tempa[t]=temp[p];
						t++;
					}		
				}
				listassign=Arrays.asList(tempa);
			}
			else
				listassign=null;
			return "listassignsuccess";
			
		/*	
		if(cid!=null&&(!cid.equals("qaz"))&&csn!=null&&(!csn.equals("wsx"))){
			if(assignmentsn!=null&&assignmentsn.equals("-1"))
			listassign=assignmentservice.getAllAssignByCidCsn(cid,csn);
			else
			listassign=assignmentservice.getAllAssignByCidCsnAsn(cid, csn,assignmentsn);
		}*/
		
	}
	
	public String downloadtemplate(){
		FileWriter fileWriter=null;
		CSVPrinter csvFilePrinter=null;
		//创建 CSVFormat
        CSVFormat csvFileFormat = CSVFormat.DEFAULT.withRecordSeparator(NEW_LINE_SEPARATOR);
		try {
			//初始化FileWriter
			String filename=generateFileName("123.csv");
			fileWriter = new FileWriter(csvlocalpath+"/"+filename);
			//初始化 CSVPrinter
	        csvFilePrinter = new CSVPrinter(fileWriter, csvFileFormat);
	        //创建CSV文件头
	        csvFilePrinter.printRecord(FILE_HEADER);
	        
		assignlist=assignmentservice.getAllAssignByAsn(assignmentsn);
		List<User> tempuserlist=new  ArrayList<User>();
		for(Assign a:assignlist){
			tempuserlist.add(userservice.getUser(a.getSid()));
		}
		for(User u:tempuserlist){
			List<String> userDataRecord = new ArrayList<String>();
			userDataRecord.add(u.getId());
			userDataRecord.add(u.getRealname());
			userDataRecord.add("");
			userDataRecord.add("");
			csvFilePrinter.printRecord(userDataRecord);
		}
		fileWriter.flush();
		fileWriter.close();
		csvFilePrinter.close();
		//download
    	ServletActionContext.getRequest().setCharacterEncoding("UTF-8");
        File savedfile = new File(csvlocalpath+"/"+filename);
        inputStream = new FileInputStream(savedfile);
        fileName=new String(filename.getBytes(),"ISO8859-1");

		}catch(Exception e){
			e.printStackTrace();
			try {
				fileWriter.flush();
				fileWriter.close();
				csvFilePrinter.close();
			} catch (Exception ex) {
                ex.printStackTrace();
			}
		}
		return "downloadtemplatesuccess";
	}
	
	
	public String downloadAssign(){
		try{
	    	this.processaddress();
	    	// 有数据可以下载
	    	if (downLoadPaths.length != 0) {
	    		// 进行预处理
	    		this.preProcess();
	    	} else {
	    		// 没有文件可以下载，返回nodata
	    		return "nodata";
	    	}
	    	// 处理
	    	this.writeZip();
	    	// 后处理关闭流
	    	this.afterProcess();
	    	return null;
	    	}catch(Exception e){
	    		e.printStackTrace();
	    		return "nodata";
	    	}
	}
	
	private void processaddress(){
		downassign=assignmentservice.getAllAssignByAsn(assignmentsn);
		int count=downassign.size();
    	downLoadPaths=new String[count];
    	downLoadNames=new String[count];
		for(int i=0;i<downassign.size();i++){
			downLoadPaths[i]=localpath+"/"+downassign.get(i).getResource();
			downLoadNames[i]=downassign.get(i).getSid()+"_"+downassign.get(i).getUploadtime().toString()+"_"+downassign.get(i).getName();
		}
	}
	// 压缩处理
	 	private void writeZip() throws Exception {
	 		byte[] buf = new byte[8192];
	 		int len;
	 		
	 		for (int i=0;i<downLoadPaths.length;i++) {
	 			File file = new File(downLoadPaths[i]);
	 			if (!file.isFile())
	 				continue;
	 			ZipEntry ze = new ZipEntry(downLoadNames[i]); //apache jar的ZipEntry
	 			zos.putNextEntry(ze);
	 			BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
	 			while ((len = bis.read(buf)) > 0) {
	 				zos.write(buf, 0, len);
	 			}
	 			bis.close();
	 			zos.closeEntry();
	 		}
	 	}

	 	// 预处理
	 	private void preProcess() throws Exception {
	 		HttpServletResponse response = ServletActionContext.getResponse();
	 		res = response.getOutputStream();
	 		// 清空输出流(在迅雷下载不会出现一长窜)
	 		response.reset();
	 		// 设定输出文件头
	 		response.setHeader("Content-Disposition", "attachment;filename=ArchivedAssignment_"+generateFileName("ArchivedPPT.zip"));
	 		response.setContentType("application/zip");
	 		zos = new ZipOutputStream(res);
	 	}

	 	// 后处理
	 	private void afterProcess() throws Exception {

	 		zos.close();
	 		res.close();
	 	}
	
	public String uploadScore() throws Exception{
		ServletActionContext.getRequest().setCharacterEncoding("UTF-8");
		if (doc != null) {
	        File savedir=new File(uploadcsvlocalpath);
	        if(!savedir.getParentFile().exists())
	            savedir.getParentFile().mkdirs();
	        String filename=generateFileName(docFileName);
	        File savefile = new File(savedir, filename);
	        FileUtils.copyFile(doc, savefile);
	        FileReader fileReader = null;
			CSVParser csvFileParser = null;
			//创建CSVFormat（header mapping）
	        CSVFormat csvFileFormat = CSVFormat.EXCEL.withHeader("学号,姓名,分数,评语");
	        try {
	            //初始化FileReader object
	            fileReader = new FileReader(uploadcsvlocalpath+"/"+filename);
	            //初始化 CSVParser object
	            csvFileParser = new CSVParser(fileReader, csvFileFormat);
	            //CSV文件records
	            List<CSVRecord> csvRecords = csvFileParser.getRecords();
	            //List<> userList = new ArrayList<>();
	            // 
	            for (int i = 1; i < csvRecords.size(); i++) {
	            	CSVRecord record = csvRecords.get(i);
	            	//创建对象填入数据
	            	Assign temp=assignmentservice.getAssignBySidAsn(record.get(0),radio);
	            	assignmentservice.saveNewScore(temp.getAssignmentid(),record.get(2),record.get(3));	
				}
	            
	        } 
	        catch (Exception e) {
	            e.printStackTrace();
	        } finally {
	            try {
	                fileReader.close();
	                csvFileParser.close();
	            } catch (Exception e) {
	                e.printStackTrace();
	            }
	        }
	    }
		return "submitsuccess";

	}
	 	
	public AssignmentService getAssignmentservice() {
		return assignmentservice;
	}
	public void setAssignmentservice(AssignmentService assignmentservice) {
		this.assignmentservice = assignmentservice;
	}
	public static long getSerialversionuid() {
		return serialVersionUID;
	}
	public CourseService getCourseservice() {
		return courseservice;
	}
	public void setCourseservice(CourseService courseservice) {
		this.courseservice = courseservice;
	}
	public List<CourseJiaoke> getCj() {
		return cj;
	}
	public void setCj(List<CourseJiaoke> cj) {
		this.cj = cj;
	}

	public String[] getCheckbox() {
		return checkbox;
	}

	public void setCheckbox(String[] checkbox) {
		this.checkbox = checkbox;
	}

	public String getAssignmentname() {
		return assignmentname;
	}

	public void setAssignmentname(String assignmentname) {
		this.assignmentname = assignmentname;
	}

	public String getDescription() {
		return description;
	}

	public void setDescription(String description) {
		this.description = description;
	}

	public String getDuetime() {
		return duetime;
	}

	public void setDuetime(String duetime) {
		this.duetime = duetime;
	}

	public Assignment getAs() {
		return as;
	}

	public void setAs(Assignment as) {
		this.as = as;
	}

	public List<Assign> getAssign() {
		return assign;
	}

	public void setAssign(List<Assign> assign) {
		this.assign = assign;
	}

	public String getAid() {
		return aid;
	}

	public void setAid(String aid) {
		this.aid = aid;
	}

	public boolean isTimeflag() {
		return timeflag;
	}

	public void setTimeflag(boolean timeflag) {
		this.timeflag = timeflag;
	}

	public Assign getAss() {
		return ass;
	}

	public void setAss(Assign ass) {
		this.ass = ass;
	}

	public boolean isSubmitflag() {
		return submitflag;
	}

	public void setSubmitflag(boolean submitflag) {
		this.submitflag = submitflag;
	}

	public File getDoc() {
		return doc;
	}

	public void setDoc(File doc) {
		this.doc = doc;
	}

	public String getDocFileName() {
		return docFileName;
	}

	public void setDocFileName(String docFileName) {
		this.docFileName = docFileName;
	}

	public String getDocContentType() {
		return docContentType;
	}

	public void setDocContentType(String docContentType) {
		this.docContentType = docContentType;
	}

	public static String getLocalpath() {
		return localpath;
	}

	public static void setLocalpath(String localpath) {
		AssignmentAction.localpath = localpath;
	}

	public Assignmentcontent getAsc() {
		return asc;
	}

	public void setAsc(Assignmentcontent asc) {
		this.asc = asc;
	}

	public List<CourseJiaoke> getC1() {
		return c1;
	}

	public void setC1(List<CourseJiaoke> c1) {
		this.c1 = c1;
	}

	public List<CourseJiaoke> getC2() {
		return c2;
	}

	public void setC2(List<CourseJiaoke> c2) {
		this.c2 = c2;
	}

	public List<Assign> getA1() {
		return a1;
	}

	public void setA1(List<Assign> a1) {
		this.a1 = a1;
	}

	public String getCid() {
		return cid;
	}

	public void setCid(String cid) {
		this.cid = cid;
	}

	public String getCsn() {
		return csn;
	}

	public void setCsn(String csn) {
		this.csn = csn;
	}

	public String getAssignmentsn() {
		return assignmentsn;
	}

	public void setAssignmentsn(String assignmentsn) {
		this.assignmentsn = assignmentsn;
	}

	public CourseJiaoke getTempc2() {
		return tempc2;
	}

	public void setTempc2(CourseJiaoke tempc2) {
		this.tempc2 = tempc2;
	}

	public Assign getTempa1() {
		return tempa1;
	}

	public void setTempa1(Assign tempa1) {
		this.tempa1 = tempa1;
	}

	public CourseJiaoke getTempc1() {
		return tempc1;
	}

	public void setTempc1(CourseJiaoke tempc1) {
		this.tempc1 = tempc1;
	}

	public List<Assign> getListassign() {
		return listassign;
	}

	public void setListassign(List<Assign> listassign) {
		this.listassign = listassign;
	}

	public List<Assign> getAssignlist() {
		return assignlist;
	}

	public void setAssignlist(List<Assign> assignlist) {
		this.assignlist = assignlist;
	}

	public UserService getUserservice() {
		return userservice;
	}

	public void setUserservice(UserService userservice) {
		this.userservice = userservice;
	}



	public InputStream getInputStream() {
		return inputStream;
	}

	public void setInputStream(InputStream inputStream) {
		this.inputStream = inputStream;
	}

	public String getFileName() {
		return fileName;
	}

	public void setFileName(String fileName) {
		this.fileName = fileName;
	}

	public static String getCsvlocalpath() {
		return csvlocalpath;
	}

	public static void setCsvlocalpath(String csvlocalpath) {
		AssignmentAction.csvlocalpath = csvlocalpath;
	}

	public static String getNewLineSeparator() {
		return NEW_LINE_SEPARATOR;
	}

	public static Object[] getFileHeader() {
		return FILE_HEADER;
	}

	public List<Assign> getDownassign() {
		return downassign;
	}

	public void setDownassign(List<Assign> downassign) {
		this.downassign = downassign;
	}

	public String[] getDownLoadPaths() {
		return downLoadPaths;
	}

	public void setDownLoadPaths(String[] downLoadPaths) {
		this.downLoadPaths = downLoadPaths;
	}

	public String[] getDownLoadNames() {
		return downLoadNames;
	}

	public void setDownLoadNames(String[] downLoadNames) {
		this.downLoadNames = downLoadNames;
	}

	public OutputStream getRes() {
		return res;
	}

	public void setRes(OutputStream res) {
		this.res = res;
	}

	public ZipOutputStream getZos() {
		return zos;
	}

	public void setZos(ZipOutputStream zos) {
		this.zos = zos;
	}

	public static String getUploadcsvlocalpath() {
		return uploadcsvlocalpath;
	}

	public static void setUploadcsvlocalpath(String uploadcsvlocalpath) {
		AssignmentAction.uploadcsvlocalpath = uploadcsvlocalpath;
	}

	public String getRadio() {
		return radio;
	}

	public void setRadio(String radio) {
		this.radio = radio;
	}

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	public List<CourseJiaoke> getCr() {
		return cr;
	}

	public void setCr(List<CourseJiaoke> cr) {
		this.cr = cr;
	}

	public String getChkbox() {
		return chkbox;
	}

	public void setChkbox(String chkbox) {
		this.chkbox = chkbox;
	}


}
